import { Component } from 'vue-property-decorator';

import { ObjectValue, isString, runExpression } from '../../vendors/handie';
import { EnumFieldOption, EnumField } from '../../vendors/handie/types/input';

import { resolveEnumOptions } from '../helper';
import FieldHeadlessWidget from './Field';

interface ResolvedOption extends Omit<EnumFieldOption, 'available'> {
  disabled: boolean;
}

@Component
export default class BaseEnumFieldHeadlessWidget<ValueType> extends FieldHeadlessWidget<ValueType> {
  protected internalOptions: EnumFieldOption[] = [];

  protected options: ResolvedOption[] = [];

  private resolveOptions(record: ObjectValue): ResolvedOption[] {
    const resolved: ResolvedOption[] = [];

    this.internalOptions.forEach(({ available, ...others }) => {
      let optionAvailable = true;

      if (isString(available)) {
        optionAvailable = runExpression({ value: record }, available!);
      }

      let disabled = false;

      if (!optionAvailable) {
        let { showUnavailableOption } = this.config;

        if (showUnavailableOption === undefined) {
          showUnavailableOption = this.getCommonBehavior('field.showUnavailableOption');
        }

        if (showUnavailableOption !== true) {
          return;
        }

        disabled = true;
      }

      resolved.push({ ...others, disabled });
    });

    return resolved;
  }

  protected created(): void {
    resolveEnumOptions(this.context, this.field as EnumField, options => {
      this.internalOptions = options;
      this.options = this.resolveOptions(this.context.getValue());

      if (this.internalOptions.some(({ available }) => isString(available))) {
        this.on('change', value => (this.options = this.resolveOptions(value)));
      }
    });
  }
}
